package com.java.TCP.upload_file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);

        while (true) {
            Socket socket = serverSocket.accept();

            String fileName = UUID.randomUUID().toString();
            String path = "网络编程\\com\\java\\TCP\\upload_file\\files\\" + fileName + ".jpg";
            BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(path));

            // 将接收到的文件写到本地
            int length;
            byte[] buffer = new byte[1024];
            while ((length = bufferedInputStream.read(buffer)) != -1) {
                bufferedOutputStream.write(buffer, 0, length);
            }

            // 发送上传成功或失败的反馈给客户端
            socket.getOutputStream().write("上传成功".getBytes());
            socket.close();
        }
    }
}
